package com.qst.crop.controller;

import com.qst.crop.common.Result;
import com.qst.crop.common.StatusCode;
import com.qst.crop.entity.Address;
import com.qst.crop.security.entity.JwtUser;
import com.qst.crop.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/address")
public class AddressController {
    @Autowired
    private AddressService addressService;

    @PostMapping("/add")
    public Result<Integer> add(@RequestBody Address address){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        JwtUser principal = (JwtUser) authentication.getPrincipal();
        String username = principal.getUsername();
        address.setOwnName(username);

        if(address.getIsDefault()){
            // 如果添加为默认地址，删除其他默认地址
            addressService.setDefaultAddress(username);
        }

        return new Result<>(true, StatusCode.OK,"insert success", addressService.add(address));
    }

    @GetMapping("/selectByOwnName")
    public Result<List<Address>> selectByOwnName(){

        return new Result<>(true,StatusCode.OK,"查询成功",addressService.selectByOwnName());
    }


    @PostMapping("/defaultAddressInfoUpdate")
    public Result<Integer> defaultAddressInfoUpdate(@RequestBody Address address){
        if(address.getIsDefault()){
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            JwtUser principal = (JwtUser) authentication.getPrincipal();
            String username = principal.getUsername();
            addressService.setDefaultAddress(username);
        }
        return new Result<>(true,StatusCode.OK,"修改成功",addressService.updateByPrimaryKey(address));
    }

    @DeleteMapping("/delete/{id}")
    public Result<Integer> deleteByPrimaryKey(@PathVariable("id")Integer id){
        return new Result<>(true,StatusCode.OK,"删除成功", addressService.deleteByPrimaryKey(id));
    }

    @GetMapping("/selectDefaultByOwnName")
    public Result<Address> selectDefaultByOwnName(){
        return new Result<>(true,StatusCode.OK,"查询默认地址成功",addressService.selectDefaultByOwnName());
    }
}
